/*
 * Copyright 2010-2012 Susanta Tewari. <freecode4susant@users.sourceforge.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package coalescent.data;

import coalescent.model.PopGenModel;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;

import commons.core.Data;
import commons.core.Singletons;
import commons.util.ExceptionUtil;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;

import java.util.Map;

/**
 * Data under a population genetic model.
 *
 * @param <A> allele type
 * @param <E> enum of event types for this data model
 * @param <M> the data model (subtype of {@code PopGenModel})
 * @param <R> the runtime type of this class
 * @author Susanta Tewari
 * @since 1.5
 */
public abstract class PopGenData<A, E extends Enum<E>, M extends PopGenModel<E>,
                                 R extends PopGenData<A, E, M, R>> extends Data<M, R> {

    /** Field description */
    private final ImmutableMap<A, Integer> alleleFreq;

    /**
     * Initializes the model and the allele frequencies. The allele frequency map is made
     * unmodifiable.
     *
     * @param model the data model
     * @param alleleFreq allele frequency
     * @throws NullPointerException if any of the parameter is {@code null}
     * @throws IllegalArgumentException if {@code alleleFreq} is empty
     */
    public PopGenData(M model, Map<A, Integer> alleleFreq) {

        super(model);

        if (alleleFreq == null) ExceptionUtil.throwIllegalArgExNull("alleleFreq");
        if (alleleFreq.isEmpty())
            ExceptionUtil.throwIllegalArgEx(getClass(), "Map_Is_Empty", "alleleFreq");

        this.alleleFreq = ImmutableMap.copyOf(alleleFreq);
    }

    /**
     * Method description
     *
     *
     * @return
     */
    protected final ImmutableMap<A, Integer> getAlleleFreq() {
        return alleleFreq;
    }

    /**
     * Method description
     *
     *
     * @return
     */
    @Override
    public abstract MutablePopGenData<A, M, R> getMutable();

    /**
     * The total number of alleles (distinct) in this data set.
     *
     * @return the total number of distinct alleles
     */
    public final int getAlleleCount() {
        return alleleFreq.size();
    }

    /**
     * The number of observations of the specified allele in this data set.
     *
     * @param allele an allele in this data set
     * @return frequency of the specified allele
     */
    public final int getAlleleFrequency(A allele) {

        checkAllelePresent(allele);

        return alleleFreq.get(allele);
    }

    /**
     * Throws {@code IllegalArgumentException} if the parameter {@code allele} is not present in
     * this data set.
     *
     * @param allele allele supposedly present in this data set
     */
    protected final void checkAllelePresent(A allele) {

        if (allele == null) {
            ExceptionUtil.throwIllegalArgExNull("allele");
        }

        if (!getAlleles().contains(allele)) {
            ExceptionUtil.throwIllegalArgEx(getClass(), "Allele_Not_Present", allele);
        }
    }

    /**
     * Only some alleles are ready to undergo an event of a specified type.
     *
     * @param eventType an event type of this data model. All values of the enum type {@code E} are
     * supported.
     * @return alleles ready to undergo an event of the given type
     */
    public abstract ImmutableSet<A> getAlleles(E eventType);

    /**
     * The alleles (distinct) of this data set.
     *
     * @return the alleles of this data set
     */
    public final ImmutableSet<A> getAlleles() {
        return alleleFreq.keySet();
    }

    /**
     * Checks if the data is an MRCA. It is an MRCA if the sample size is 1.
     *
     * @return {@code true} if it is MRCA; {@code false} otherwise
     */
    public boolean isMRCA() {
        return getSampleSize() == 1;
    }

    /**
     * Method description
     *
     *
     * @return
     */
    @Override
    public final int getSampleSize() {

        int sum = 0;

        for (A k : getAlleles()) {

            sum += getAlleleFrequency(k);
        }

        return sum;
    }

    /**
     * Two {@code Data} instances are equal if they have equal models and equal allele-frequency
     * pairs.
     *
     * @param obj the object to compare against
     * @return {@code false} if 1) {@code obj} is {@code null} 2) from a different class 3) have
     *         different model objects (based on {@code equals}) 4) have different allele frequencies;
     *         {@code true} otherwise
     */
    @Override
    public boolean equals(Object obj) {

        if (obj == null) {
            return false;
        }

        if (obj == this) {
            return true;
        }

        if (getClass() != obj.getClass()) {
            return false;
        }

        //J-
        @SuppressWarnings("unchecked")
        //J+
        final PopGenData<A, E, M, R> other = (PopGenData<A, E, M, R>) obj;

        return new EqualsBuilder().appendSuper(super.equals(obj)).append(alleleFreq,
                other.alleleFreq).isEquals();
    }

    /**
     * Computes hash code based on the data model and allele-frequency pairs.
     *
     * @return hash code based on the data model and allele-frequency pairs
     */
    @Override
    public int hashCode() {
        return new HashCodeBuilder().appendSuper(super.hashCode()).append(alleleFreq).toHashCode();
    }

    /**
     * Contains information on data model and allele frequencies.
     *
     * @return information on data model and allele frequencies.
     */
    @Override
    public String toString() {

        return new ToStringBuilder(this, Singletons.TO_STRING_STYLE).appendSuper(
            super.toString()).append("allele-frequency", alleleFreq).toString();
    }
}
